package com.cloud.elasticsearc.service;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ElasticSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void findAll(String index,int size) throws Exception {
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types("_doc");
        SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        sourceBuilder.query(boolQueryBuilder);
        List<QueryBuilder> mustQueryList = boolQueryBuilder.must();
        mustQueryList.add(QueryBuilders.termQuery("trace_id", "?"));
        mustQueryList.add(QueryBuilders.termQuery("tags", "?"));
        sourceBuilder.size(size);
        sourceBuilder.sort("latency", SortOrder.DESC);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest,null);
        log.info("totalhits:{}", searchResponse.getHits().getTotalHits());
        SearchHit[] searchHits = searchResponse.getHits().getHits();
    }

}
